from django import forms
from django.contrib.auth import login

from user.models import User
from django_redis import get_redis_connection
import re
from django.db.models import Q
from fail_time.fail_time import FailTime
class RegisterForm(forms.Form):
    username=forms.CharField(max_length=20,min_length=6,
                             error_messages={
                                 "max_length":"用户名长度超出范围",
                                 "min_length":"用户名长度超出范围",
                                 "required":"用户名不能为空",
                             })
    password = forms.CharField(max_length=20, min_length=6,
                               error_messages={
                                   "max_length": "密码长度超出范围",
                                   "min_length": "密码长度超出范围",
                                   "required": "密码不能为空",
                               })
    password_repeat = forms.CharField(max_length=20, min_length=6,
                               error_messages={
                                   "max_length": "密码长度超出范围",
                                   "min_length": "密码长度超出范围",
                                   "required": "密码不能为空",
                               })
    mobile = forms.CharField(max_length=11, min_length=11,
                               error_messages={
                                   "max_length": "手机号长度超出范围",
                                   "min_length": "手机号长度超出范围",
                                   "required": "手机号不能为空",
                               })
    smscode = forms.CharField(max_length=4, min_length=4,
                               error_messages={
                                   "max_length": "短信长度超出范围",
                                   "min_length": "短信长度超出范围",
                                   "required": "短信不能为空",
                               })
    def __init__(self,*args,**kwargs):
        self.request=kwargs.pop("request",None)
        super().__init__(*args,**kwargs)

    def clean_username(self):
        username=self.cleaned_data.get("username")
        if username:
            if User.objects.filter(username=username):
                raise forms.ValidationError("用户名已经注册")
        else:
            raise forms.ValidationError("用户名不能为空")
        return username
    def clean(self):
        clean_data=super().clean()
        password=clean_data.get("password")
        re_password=clean_data.get("password_repeat")
        mobile=clean_data.get("mobile")
        smscode=clean_data.get("smscode")
        if not password:
            raise forms.ValidationError("密码不能为空")
        if password != re_password:
            raise forms.ValidationError("密码不一致,请重新输入")
        if not mobile:
            raise forms.ValidationError("手机号不能为空")
        redis_conn=get_redis_connection("smscode")
        sms=redis_conn.get('text_flag_{}'.format(mobile))
        if smscode != sms.decode("utf-8"):
            raise forms.ValidationError("短信验证码错误")


class LoginForm(forms.Form):
    account = forms.CharField(error_messages={
        "required": "账号不能为空",
    })
    password = forms.CharField(max_length=20, min_length=5,
                               error_messages={
                                   "max_length": "密码长度超出范围",
                                   "min_length": "密码长度超出范围",
                                   "required": "密码不能为空",
                               })
    remember = forms.BooleanField(required=False)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super().__init__(*args, **kwargs)

    def clean_account(self):
        account = self.cleaned_data.get("account")
        if account:
            if not (re.match('^1[3-9]\d{9}$', account) or (len(account)>5 or len(account)<20)):
                raise forms.ValidationError("账号格式错误")
        else:
            raise forms.ValidationError("账号不能为空")
        return account

    def clean(self):
        clean_data = super().clean()
        account = clean_data.get("account")
        password = clean_data.get("password")
        remember = clean_data.get("remember")
        if account:
            user_queryset = User.objects.filter(Q(username=account) | Q(mobile=account))
            if user_queryset:
                user=user_queryset.filter().first()
                if not user.check_password(password):
                    raise forms.ValidationError("账号或密码不正确")
                else:
                    login(self.request,user)
                if remember:
                    self.request.session.set_expiry(FailTime.REMBER_EXPIRY)
                else:
                    self.request.session.set_expiry(0)

            else:
                raise forms.ValidationError("账号或密码不正确")
        else:
            raise forms.ValidationError("账号不能为空")